<script setup>
import { onMounted, reactive, ref, watch, onBeforeUnmount } from 'vue'
import {
    getDeviceAlarm,
    deleteAnalysisData,
    postFalseAlarmImage,
    setCleanDate,
    queryCleanDate,
} from '@/assets/api/api'
import { showMsg, showConfirm } from '@/assets/js/utils'
import { ElMessageBox } from 'element-plus'
import config from '@/assets/js/config'
import { useUserStore } from '@/stores/index'
const userStore = useUserStore()

const formData = reactive({})
// const algorithmList = [
//     {
//         value: '1',
//         label: '人员跌倒',
//     },
//     {
//         value: '2',
//         label: '烟雾检测',
//     },
// ]
const algorithmList = [
    '区域入侵',
    '对象滞留',
    '物体检测',
    '姿势检测',
    '越界检测',
    '区域交叉',
    '违规占道',
    '人员跌倒',
    '接打电话检测',
    '烟雾识别',
    '安全帽识别',
    '脱岗离岗报警',
]
const tableData = ref([])
const shortcuts = [
    {
        text: '上周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: '上个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: '前三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]
const multipleSelection = ref([])
const currentPage = ref(1)
const pageSize = 10
const total = ref(0)
const ruleFormRef = ref()
function handleSelectionChange(val) {
    multipleSelection.value = val
}
function deleteData(item) {
    showConfirm({
        content: '您确定要删除该数据吗',
        onConfirm: () => {
            deleteAnalysisData({ id: item.id }).then(() => {
                showMsg('删除成功')
                getData(currentPage.value, formData)
            })
        },
    })
}
function falseAlarm(item) {
    ElMessageBox.confirm('您确定要上传该误报图片吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            postFalseAlarmImage({
                algorithmName: item.alarm_type_name,
                url: item.image_path,
            }).then(() => {
                showMsg('上传成功')
                getData(currentPage.value, formData)
            })
        })
        .catch(() => {
            showMsg('上传失败', 'error')
        })
}
function handleCurrentChange(e) {
    //换页
    currentPage.value = e
    getData(currentPage.value, formData)
}
function getData(page = 1, item) {
    console.log(item)
    const params = {
        page,
        limit: pageSize,
        deviceClassify: 1,
        ...(item && { ...item }),
    }
    if (item) {
        delete params.timeDate
    }
    getDeviceAlarm(params).then((res) => {
        const { Items, totalSize } = res.data
        tableData.value = Items
        currentPage.value = +res.data.currentPage
        total.value = totalSize
    })
}
function resetForm(formEl) {
    if (!formEl) return
    formEl.resetFields()
}
watch(
    () => formData.timeDate,
    (value) => {
        if (value) {
            formData.start_time = value[0]
            formData.end_time = value[1]
        } else {
            formData.start_time = undefined
            formData.end_time = undefined
        }
    }
)
// getData()
const ws = new WebSocket(config.socketUrl)
function openSocket() {
    //  //连接发生错误的回调方法
    ws.onerror = function () {
        console.log('ws连接发生错误')
    }
    //连接成功建立的回调方法
    ws.onopen = function () {
        console.log('ws连接成功')
    }
    //接收到消息的回调方法
    ws.onmessage = function () {
        console.log('更新')
        getData(currentPage.value, formData)
        // ws.close()
    }
    //连接关闭的回调方法
    ws.onclose = function () {
        console.log('ws连接关闭')
    }
}
onMounted(() => {
    openSocket()
})
onBeforeUnmount(() => {
    //连接关闭的回调方法
    ws.close()
})
const saveTime = ref()
const editData = ref(true)
function setSaveTime() {
    setCleanDate({
        clean_date: saveTime.value,
        license_information: userStore.systemInfo.gatewayPermit,
    }).then((res) => {
        if (res.code == 0) {
            alarmImgTime.value = false
            showMsg('操作成功')
        }
    })
}
const alarmImgTime = ref(false)

function getSaveTime() {
    queryCleanDate({
        license_information: userStore.systemInfo.gatewayPermit,
    }).then((res) => {
        saveTime.value = res.data
        alarmImgTime.value = true
    })
}
</script>

<template>
    <div class="filter-box white-box d-flex" style="padding: 0.05rem">
        <el-form
            :inline="true"
            :model="formData"
            ref="ruleFormRef"
            class="d-flex-1"
        >
            <el-form-item prop="timeDate">
                <el-date-picker
                    v-model="formData.timeDate"
                    type="datetimerange"
                    unlink-panels
                    range-separator="-"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :shortcuts="shortcuts"
                    value-format="YYYY-MM-DD HH:ss:mm"
                    :clearable="false"
                />
            </el-form-item>
            <el-form-item prop="alarm_type_name">
                <el-select
                    v-model="formData.alarm_type_name"
                    class="m-2"
                    placeholder="请选择算法类型"
                >
                    <el-option
                        v-for="item in algorithmList"
                        :key="item"
                        :label="item"
                        :value="item"
                    />
                </el-select>
            </el-form-item>
            <el-form-item prop="device_name">
                <el-input
                    placeholder="请输入通道名称"
                    v-model="formData.device_name"
                />
            </el-form-item>
            <el-button type="primary" @click="getData(1, formData)"
                >查询</el-button
            >
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form>
    </div>
    <div class="white-box d-flex-1 mt-10">
        <div class="fl-bw">
            <div class="fs-16 mb-10">
                <span class="icon" style="color: var(--el-color-primary)"
                    >&#xe608;</span
                >实时报警数据
            </div>

            <el-button @click="getSaveTime">设置报警图片保存时间</el-button>
            <!-- <span class="fs-14">报警图片保存时间</span>
                <el-input
                    v-model="saveTime"
                    class="ml-10"
                    style="width: 25%"
                    :disabled="editData"
                />（天）
                <el-button @click="editData = false" class="ml-10"
                    >编辑</el-button
                >
                <el-button type="primary" @click="setSaveTime">保存</el-button> -->
        </div>
        <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column
                prop="alarm_type_name"
                label="算法名称"
                width="120"
            />
            <el-table-column property="number" label="通道ID" width="160" />
            <el-table-column
                property="device_name"
                label="通道名称"
                width="200"
            />
            <el-table-column property="position" label="通道位置" width="200" />
            <el-table-column property="alarm_time" label="报警时间" />
            <el-table-column label="报警图片" width="180">
                <template #default="scope">
                    <el-image
                        style="width: 100%; height: 100px"
                        :zoom-rate="1.2"
                        fit="cover"
                        :src="
                            scope.row.image_path.replace(
                                'http://192.168.0.80',
                                config.imgUrl
                            )
                        "
                        :preview-src-list="[
                            scope.row.image_path.replace(
                                'http://192.168.0.80',
                                config.imgUrl
                            ),
                        ]"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope"
                    ><el-button
                        @click="deleteData(scope.row)"
                        link
                        type="danger"
                        >删除</el-button
                    ><el-button
                        @click="falseAlarm(scope.row)"
                        link
                        type="primary"
                        >误报</el-button
                    ></template
                >
            </el-table-column>
        </el-table>
        <div class="mt-10 fl-bw">
            <div></div>
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                layout="prev, pager, next, jumper"
                v-model:total="total"
                @current-change="handleCurrentChange"
            />
        </div>
        <el-dialog
            :model-value="alarmImgTime"
            title="设置报警图片保存时间"
            width="600px"
            :draggable="true"
            @close="alarmImgTime = false"
        >
            <el-form ref="formRef">
                <el-form-item label="报警图片保存时间" prop="handlePerson">
                    <el-input
                        v-model="saveTime"
                        class="ml-10"
                        style="width: 25%"
                        type="number"
                    />（天）
                </el-form-item>
                <div style="color: red" class="mt-10">
                    超过保存时间的图片自动被清理，无法恢复，仅保留文字记录。
                </div>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="alarmImgTime = false">取消</el-button>
                    <el-button type="primary" @click="setSaveTime">
                        保存
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
::v-deep(.el-form-item) {
    margin-bottom: 0;
}
.white-box {
    overflow: auto !important;
}
::v-deep(.demo-image__error) {
    .el-image {
        width: 100%;
        height: 200px;
    }
}
::v-deep(.el-table__cell) {
    position: static !important; // 解决el-image 和 el-table冲突层级冲突问题
}
</style>
